<?php

namespace common\logics\order;

use Yii;
use yii\db\Exception;
use common\models\shop\ShopStore;
use common\models\shop\ShopOrderOutbound;

/**
 * 订单逻辑模型
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class OrderLogic extends \common\models\shop\ShopOrder {

    /**
     * 订单操作类型
     * @var string
     */
    const HANDLE_CANCEL = 'cancel';
    const HANDLE_DELETE = 'delete';
    const HANDLE_PAY = 'pay';
    const HANDLE_REFUND = 'refund';
    const HANDLE_LOGISTICS = 'logistics';
    const HANDLE_RECEIVE = 'receive';
//    const HANDLE_EVALUATE = 'evaluate';
    const HANDLE_SERVICE = 'service';

    /**
     * 订单操作
     */
    use OrderHandleTrait;

    /**
     * {@inheritdoc}
     */
    public function getHandleButtons() {
        return static::getConstants('handle');
    }

    /**
     * 订单状态文本
     * @return string
     */
    public function getStatusText() {
        if ($this->status == static::STATUS_CLOSE) {
            return '已关闭';
        }
        if ($this->status == static::STATUS_CANCEL) {
            return '已取消';
        }
        if ($this->isPay) {
            if ($this->refund && $this->refund->isProcessing) {
                return '退款处理中';
            }
            if ($this->status === static::STATUS_SHIPPING) {
                return '正在出库';
            } elseif ($this->status === static::STATUS_SHIP) {
                return '已发货';
            } elseif ($this->status === static::STATUS_SHIPPED) {
                return '待收货';
            } elseif ($this->status >= static::STATUS_RECEIVED) {
                return '已完成';
            } else {
                return '已付款';
            }
        }
        if (!$this->isExpired) {
            return '等待付款';
        }
        return '已取消';
    }

    /**
     * 是否显示状态颜色
     * @return bool
     */
    public function getStatusColor() {
        if ($this->status < 0) {
            return false;
        }
        if ($this->isPay) {
            if ($this->status >= static::STATUS_RECEIVED) {
                return false;
            }
            return true;
        }
        if (!$this->isExpired) {
            return true;
        }
        return false;
    }

    /**
     * 订单商品件数
     * @return integer
     */
    public function getNums() {
        $nums = $this->getGoods()->sum('goods_number');
        return intval($nums);
    }

    /**
     * 订单关联店铺
     * @return \common\db\ActiveQuery
     */
    public function getStore() {
        if (!$this->isPay && $this->unifiedOrderStores > 1) {
            return ShopStore::plateform();
        }
        return $this->hasOne(ShopStore::class, ['id' => 'store_id']);
    }

    /**
     * 订单商品信息
     * @return \common\db\ActiveQuery
     */
    public function getGoods() {
        if ($this->isPay) {
            return $this->hasMany(OrderGoodsLogic::class, ['order_id' => 'id']);
        }
        return $this->hasMany(OrderGoodsLogic::class, ['unified_id' => 'unified_id']);
    }

    /**
     * 订单应付金额
     * @return integer
     */
    public function getPayAmount() {
        if ($this->isPay) {
            return round($this->pay - $this->pay_credit / 10, 2);
        }
        return $this->unified->pay;
    }

    /**
     * 订单支付金额文本
     * @return string
     */
    public function getPayText() {
        if ($this->isPay) {
            $text = '实付';
            $amount = $this->pay - $this->pay_credit / 10;
        } else {
            $text = '需付款 ';
            $amount = $this->unified->pay;
        }
        return Yii::t('message', '{text}{amount}', [
            'text' => $text,
            'amount' => Yii::$app->formatter->asCurrency($amount),
        ]);
    }

    /**
     * 订单支付积分抵扣文本
     * @return string
     */
    public function getPayCredit() {
        if (!$this->isPay || !$this->pay_credit) {
            return '';
        }
        return Yii::t('message', '积分抵扣{amount}', [
            'amount' => Yii::$app->formatter->asCurrency($this->pay_credit / 10),
        ]);
    }

    /**
     * 订单ID（已支付订单返回商铺订单ID、未支付订单返回统一下单ID）
     * @return integer
     */
    public function getOrderId() {
        if ($this->isPay) {
            return $this->id;
        }
        return $this->unified_id;
    }

    /**
     * 订单自动出库
     * {@inheritdoc}
     */
    public function autoOutbound() {
        if ($this->canOutbound === false) {
            return null;
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $model = new ShopOrderOutbound();
            $model->setAttributes([
                'order_id' => $this->id,
                'placetime' => $this->pay_time + rand(2, 10),
                'mark' => '系统自动出库',
                'status' => ShopOrderOutbound::STATUS_ACTIVE,
            ]);
            if (!$model->save()) {
                throw new Exception($model->getErrorMsg());
            }
            $this->status = static::STATUS_SHIPPING;
            if (!$this->save()) {
                throw new Exception($this->getErrorMsg());
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $msg = $e->getMessage();
            Yii::error($msg);
            return null;
        }
        return $model;
    }

    /**
     * @inheritdoc
     */
    public function fields() {
        return [
            'id' => 'orderId',
            'order_no',
            'status_text' => 'statusText',
            'status_color' => 'statusColor',
            'pay_text' => 'payText',
            'pay_credit' => 'payCredit',
            'nums',
            'handle',
            'mark',
            'goods',
            'store',
            'weblink',
        ];
    }

}
